<template>
	<view class="container page-container">
		<custom-nav-bar title="露营地预订与攻略平台" :show-back="false">
		</custom-nav-bar>
		<view class="content">
			<!-- 1.0 搜索区域 -->
			<view class="search-section">
				<view class="location-select" @tap="showCityPicker">
					<text class="location-name">{{ currentCity }}</text>
					<text class="location-icon">▼</text>
				</view>
				<view class="search-box">
					<text class="search-icon">🔍</text>
					<input class="search-input" type="text" v-model="searchKey" placeholder="搜索营地名称或地址"
						@input="onSearch" />
				</view>
			</view>

			<!-- 2.0 轮播图区域 -->
			<view class="swiper-section">
				<swiper class="banner-swiper" circular autoplay indicator-dots>
					<swiper-item v-for="item in swiperList" :key="item.id">
						<image :src="item.imageUrl" mode="aspectFill" class="banner-image" />
					</swiper-item>
				</swiper>
			</view>

			<!-- 3.0 分类选项 -->
			<view class="category-section">
				<view class="category-item" v-for="item in categories" :key="item.id"
					:class="{ 'active': currentCategory === item.id }" @tap="switchCategory(item)">
					<text>{{ item.name }}</text>
				</view>
			</view>

			<!-- 4.0 营地列表部分修改 -->
			<view class="camp-section">
				<view class="section-header">
					<text class="section-title">推荐营地</text>
				</view>
				<scroll-view class="camp-scroll" scroll-y>
					<view class="camp-list">
						<!-- 直接使用 filteredCampList，显示所有筛选结果 -->
						<view class="camp-item" v-for="camp in filteredCampList" :key="camp.id" @tap="onCampTap(camp)">
							<image :src="camp.imageUrl" mode="aspectFill" class="camp-image" />
							<view class="camp-info">
								<text class="camp-name">{{ camp.name }}</text>
								<view class="camp-meta">
									<text class="camp-score">{{ camp.score }}分</text>
									<text class="camp-distance">距离{{ camp.distance }}</text>
								</view>
								<view class="camp-price">
									<text class="price">¥{{ camp.price }}</text>
									<text class="price-label">起</text>
								</view>
							</view>
						</view>
					</view>
				</scroll-view>
			</view>

			<!-- 5.0 攻略展示部分修改 -->
			<view class="guide-section">
				<view class="section-header">
					<text class="section-title">精选攻略</text>
					<text class="section-more" @tap="onMoreGuides">查看更多</text>
				</view>
				<scroll-view class="guide-scroll" scroll-x>
					<view class="guide-list">
						<view class="guide-item" v-for="guide in guideList" :key="guide.id" @tap="onGuideTap(guide)">
							<image :src="guide.coverUrl" mode="aspectFill" class="guide-image" />
							<view class="guide-info">
								<text class="guide-title">{{ guide.title }}</text>
								<text class="guide-desc">{{ guide.desc }}</text>
							</view>
						</view>
					</view>
				</scroll-view>
			</view>
		</view>
	</view>
</template>

<script setup>
import { ref, computed, onMounted, watch } from 'vue'
import { campApi, guideApi, cityApi } from '@/api/index'
import CustomNavBar from '@/components/custom-nav-bar/custom-nav-bar.vue'

// 数据定义
const searchTimer = ref(null)
const currentCity = ref('全部')
const currentCategory = ref('0')
const searchKey = ref('')

// 轮播图数据
const swiperList = ref([])

// 分类数据
const categories = ref([{ id: '0', name: '全部' }])

// 获取分类数据
const loadCategories = async () => {
	try {
		const res = await campApi.getCategories()
		if (res.data && Array.isArray(res.data)) {
			// 确保"全部"选项始终在第一位
			categories.value = [
				{ id: '0', name: '全部' },
				...res.data
			]
		}
	} catch (error) {
		console.error('获取分类失败:', error)
		uni.showToast({
			title: '获取分类失败',
			icon: 'none'
		})
	}
}

// 城市列表数据
const cityList = ref([])

// 营地列表数据
const campList = ref([])

// 攻略列表数据
const guideList = ref([])

// 加载轮播图数据
const loadSwiperData = async () => {
	try {
		const res = await campApi.getBannerList()
		swiperList.value = res.data || []
	} catch (error) {
		console.error('加载轮播图失败:', error)
	}
}

// 加载城市列表
const loadCityList = async () => {
	try {
		const res = await cityApi.getCityList()
		if (res.data && Array.isArray(res.data)) {
			cityList.value = [{ id: 0, name: '全部' }, ...res.data]
			console.log('城市列表更新:', cityList.value)
		}
	} catch (error) {
		console.error('加载城市列表失败:', error)
		uni.showToast({
			title: '加载城市列表失败',
			icon: 'none'
		})
	}
}

// 加载营地列表
const loadCampList = async () => {
	try {
		// 查找当前选中城市的ID
		const selectedCity = cityList.value.find(city => city.name === currentCity.value)
		const params = {};

		// 只有在有选择时才添加参数
		if (currentCategory.value !== '0') {
			params.categoryId = currentCategory.value;
		}
		if (currentCity.value !== '全部' && selectedCity) {
			params.cityId = selectedCity.id;
		}
		if (searchKey.value) {
			params.keyword = searchKey.value;
		}

		console.log('请求参数:', params)
		const res = await campApi.getCampList(params)

		if (res.data) {
			campList.value = res.data
			console.log('营地列表更新:', {
				分类: currentCategory.value,
				城市: currentCity.value,
				关键词: searchKey.value,
				结果数量: res.data.length
			})
		} else {
			campList.value = []
		}
	} catch (error) {
		console.error('加载营地列表失败:', error)
		uni.showToast({
			title: '加载营地列表失败',
			icon: 'none'
		})
	}
}

// 加载攻略列表
const loadGuideList = async () => {
	try {
		const res = await guideApi.getGuideList({ limit: 5 })
		guideList.value = res.data || []
	} catch (error) {
		console.error('加载攻略列表失败:', error)
	}
}

// 筛选营地列表
const filteredCampList = computed(() => {
	if (!searchKey.value) return campList.value

	const key = searchKey.value.toLowerCase()
	return campList.value.filter(camp =>
		camp.name.toLowerCase().includes(key) ||
		camp.address.toLowerCase().includes(key)
	)
})

// 搜索处理（防抖）
const onSearch = () => {
	if (searchTimer.value) clearTimeout(searchTimer.value)
	searchTimer.value = setTimeout(() => {
		loadCampList()
	}, 300)
}

// 切换分类
const switchCategory = (category) => {
	currentCategory.value = category.id
	loadCampList()
}

// 显示城市选择器
const showCityPicker = () => {
	if (cityList.value.length === 0) {
		uni.showToast({
			title: '暂无可选城市',
			icon: 'none'
		})
		return
	}

	uni.showActionSheet({
		itemList: cityList.value.map(city => city.name),
		success: (res) => {
			const selectedCity = cityList.value[res.tapIndex]
			currentCity.value = selectedCity.name
			console.log('选择城市:', selectedCity)
			loadCampList()
		}
	})
}

// 营地点击事件
const onCampTap = (camp) => {
	// 将营地数据转换为URL参数
	const params = {
		id: camp.id,
		name: camp.name,
		imageUrl: camp.imageUrl,
		score: camp.score,
		distance: camp.distance,
		price: camp.price
	}
	const query = Object.keys(params)
		.map(key => `${key}=${encodeURIComponent(params[key])}`)
		.join('&')

	uni.navigateTo({
		url: `/pages/camp-detail/index?${query}`
	})
}

// 攻略点击事件
const onGuideTap = (guide) => {
	const params = {
		id: guide.id,
		coverUrl: guide.coverUrl,     // 修正字段名：coverUrl 而不是 icoverUrl
		views: guide.views,
		title: guide.title,
		description: guide.description,
		createdAt: guide.createdAt,
		content: guide.content,
		categoryId: guide.categoryId // 添加分类ID用于获取相关营地
	}
	// 构建查询字符串
	const queryItems = []
	for (const [key, value] of Object.entries(params)) {
		if (value !== null && value !== undefined && value !== '') {
			queryItems.push(`${key}=${encodeURIComponent(value)}`)
		}
	}
	const query = queryItems.join('&')

	uni.navigateTo({
		url: `/pages/guide-detail/index?${query}`
	})
}

// 查看更多攻略
const onMoreGuides = () => {
	uni.switchTab({
		url: '/pages/guide/index'
	})
}

// 监听分类变化
watch([currentCategory, currentCity], () => {
	loadCampList()
})

// 页面加载
onMounted(() => {
	loadSwiperData()
	loadCategories() // 加载分类数据
	loadCityList()
	loadCampList()
	loadGuideList()
})
</script>

<style>
.container {
	padding: 0;
	background: #f5f5f5;
}

/* 搜索区域样式优化 */
.search-section {
	padding: 20rpx;
	background: #ffffff;
	display: flex;
	align-items: center;
}

.location-select {
	display: flex;
	align-items: center;
	padding: 0 20rpx;
}

.location-name {
	font-size: 28rpx;
	color: #333;
	margin-right: 8rpx;
}

.location-icon {
	font-size: 24rpx;
	color: #666;
}

.search-box {
	flex: 1;
	height: 72rpx;
	background: #f5f5f5;
	border-radius: 36rpx;
	display: flex;
	align-items: center;
	padding: 0 30rpx;
}

.search-icon {
	font-size: 28rpx;
	color: #999;
	margin-right: 10rpx;
}

.search-input {
	flex: 1;
	height: 100%;
	font-size: 28rpx;
	color: #333;
}

/* 轮播图区域样式 */
.swiper-section {
	height: 300rpx;
	background: #ffffff;
}

.banner-swiper {
	height: 100%;
}

.banner-image {
	width: 100%;
	height: 100%;
}

/* 分类选项样式 */
.category-section {
	display: flex;
	background: #fff;
	padding: 20rpx;
	border-bottom: 1rpx solid #eee;
}

.category-item {
	flex: 1;
	text-align: center;
	font-size: 28rpx;
	color: #666;
	padding: 10rpx 0;
	position: relative;
}

.category-item.active {
	color: #35495e;
	font-weight: bold;
}

.category-item.active::after {
	content: '';
	position: absolute;
	bottom: -10rpx;
	left: 50%;
	transform: translateX(-50%);
	width: 40rpx;
	height: 4rpx;
	background: #35495e;
	border-radius: 2rpx;
}

/* 营地区域样式更新 */
.camp-section {
	margin-top: 20rpx;
	background: #ffffff;
	padding: 30rpx 0;
	height: 680rpx;
	/* 固定高度 */
}

.section-header {
	padding: 0 30rpx;
	margin-bottom: 20rpx;
}

.section-title {
	font-size: 32rpx;
	font-weight: bold;
	color: #333;
}

.camp-scroll {
	height: 600rpx;
}

.camp-list {
	padding: 0 30rpx;
}

.camp-item {
	margin-bottom: 30rpx;
	background: #fff;
	border-radius: 12rpx;
	overflow: hidden;
	box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.1);
}

.camp-image {
	width: 100%;
	height: 200rpx;
	border-radius: 12rpx 12rpx 0 0;
}

.camp-info {
	padding: 20rpx;
}

.camp-name {
	font-size: 28rpx;
	font-weight: bold;
	color: #333;
	margin-bottom: 12rpx;
}

.camp-meta {
	display: flex;
	align-items: center;
	margin-bottom: 12rpx;
}

.camp-score {
	color: #ff9800;
	font-size: 24rpx;
	margin-right: 16rpx;
}

.camp-distance {
	color: #999;
	font-size: 24rpx;
}

.camp-price {
	display: flex;
	align-items: baseline;
}

.price {
	color: #f56c6c;
	font-size: 32rpx;
	font-weight: bold;
}

.price-label {
	color: #999;
	font-size: 24rpx;
	margin-left: 4rpx;
}

/* 攻略区域样式更新 */
.guide-section {
	margin-top: 20rpx;
	background: #ffffff;
	padding: 30rpx 0;
}

.guide-scroll {
	width: 100%;
	white-space: nowrap;
}

.guide-list {
	display: inline-flex;
	padding: 0 20rpx;
}

.guide-item {
	display: inline-block;
	width: 300rpx;
	margin-right: 20rpx;
	border-radius: 12rpx;
	background: #fff;
	box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.1);
	overflow: hidden;
	flex-shrink: 0;
}

.guide-image {
	width: 300rpx;
	height: 200rpx;
	border-radius: 12rpx 12rpx 0 0;
}

.guide-info {
	padding: 16rpx;
	width: 100%;
	box-sizing: border-box;
}

/* 统一的头部样式 */
.section-header {
	display: flex;
	justify-content: space-between;
	align-items: center;
	padding: 0 30rpx;
	margin-bottom: 20rpx;
}

.section-title {
	font-size: 32rpx;
	font-weight: bold;
	color: #333;
}

.section-more {
	font-size: 24rpx;
	color: #999;
}

.guide-scroll {
	width: 100%;
}

.guide-image {
	width: 300rpx;
	height: 200rpx;
	border-radius: 12rpx 12rpx 0 0;
}

.guide-info {
	padding: 16rpx;
}

.guide-title {
	display: block;
	font-size: 28rpx;
	font-weight: bold;
	color: #333;
	overflow: hidden;
	text-overflow: ellipsis;
	white-space: nowrap;
}

.guide-desc {
	display: block;
	font-size: 24rpx;
	color: #999;
	margin-top: 8rpx;
	overflow: hidden;
	text-overflow: ellipsis;
	white-space: nowrap;
}

.content {
	margin-top: 80rpx;
}
</style>
